package manager

import (
	"fmt"
	"sync"
	"time"
)

// ScoreChangeRecord 记录分数变动的详细信息
type ScoreChangeRecord struct {
	ChangeAmount int       `json:"change_amount"` // 分数变动量
	ChangeTime   time.Time `json:"change_time"`   // 分数变动时间
	UserID       string    `json:"user_id"`       // 用户ID
	Reason       string    `json:"reason"`        // 分数变动原因
}

// RoomScoreData 存储每个直播间的分数数据
type RoomScoreData struct {
	CurrentScore         int                 `json:"current_score"`          // 当前分数
	ScoreHistory         []ScoreChangeRecord `json:"score_history"`          // 历史分数变动记录
	LastChangeTime       time.Time           `json:"last_change_time"`       // 上一次改动时间
	LastRoundTime        time.Time           `json:"last_round_time"`        // 上一次整点分数变动时间
	LastNotificationTime time.Time           `json:"last_notification_time"` // 上一次通知的时间
}

// ScoreManager 管理分数的变动
type ScoreManager struct {
	roomScoreData map[string]*RoomScoreData
	initRoomIds   map[string]struct{} // 已经初始化的直播间ID
	mu            sync.Mutex
}

// NewScoreManager 初始化ScoreManager
func NewScoreManager() *ScoreManager {
	return &ScoreManager{
		roomScoreData: make(map[string]*RoomScoreData),
		initRoomIds:   make(map[string]struct{}),
	}
}

// InitializeRoom 初始化特定直播间的分数数据
func (s *ScoreManager) InitializeRoom(liveRoomID string) {
	s.mu.Lock()
	defer s.mu.Unlock()

	// 初始化RoomScoreData
	s.roomScoreData[liveRoomID] = &RoomScoreData{
		CurrentScore:         0,
		ScoreHistory:         make([]ScoreChangeRecord, 0),
		LastChangeTime:       time.Now(),
		LastRoundTime:        time.Now(),
		LastNotificationTime: time.Now(),
	}

	s.initRoomIds[liveRoomID] = struct{}{}
	// close的时候执行下面的delte
	//delete(s.initRoomIds, liveRoomID)

}

// InitializeRoom 初始化特定直播间的分数数据
func (s *ScoreManager) FinalizeRoom(liveRoomID string) {
	s.mu.Lock()
	defer s.mu.Unlock()

	// close的时候执行下面的delte
	delete(s.initRoomIds, liveRoomID)
}

// 常量，每分钟增加的分数
const RoundScoreIncrement = 1000

// UpdateScore 根据礼物变动分数
func (s *ScoreManager) UpdateScore(liveRoomID string, giftScore int, userID string, reason string) {
	s.mu.Lock()
	defer s.mu.Unlock()

	roomData, exists := s.roomScoreData[liveRoomID]
	if !exists {
		// 如果房间数据不存在，则初始化
		s.InitializeRoom(liveRoomID)
		roomData = s.roomScoreData[liveRoomID]
	}

	roomData.CurrentScore += giftScore
	record := ScoreChangeRecord{
		ChangeAmount: giftScore,
		ChangeTime:   time.Now(),
		UserID:       userID,
		Reason:       reason,
	}
	roomData.ScoreHistory = append(roomData.ScoreHistory, record)
	roomData.LastChangeTime = time.Now()
	fmt.Println("分数变动因为  ", reason, "  而变动")
}

// CheckRoundScoreChange 检查是否因为时间变动分数
func (s *ScoreManager) CheckRoundScoreChange(liveRoomID string) {
	s.mu.Lock()
	defer s.mu.Unlock()

	roomData, exists := s.roomScoreData[liveRoomID]
	if !exists {
		// 如果房间数据不存在，则初始化
		s.InitializeRoom(liveRoomID)
		roomData = s.roomScoreData[liveRoomID]
	}

	// 获取当前时间
	now := time.Now()

	// 检查是否到了下一分钟
	if now.Minute() != roomData.LastRoundTime.Minute() || now.Day() != roomData.LastRoundTime.Day() || now.Month() != roomData.LastRoundTime.Month() || now.Year() != roomData.LastRoundTime.Year() {
		roomData.CurrentScore += RoundScoreIncrement // 每分钟增加分分数
		record := ScoreChangeRecord{
			ChangeAmount: RoundScoreIncrement,
			ChangeTime:   now,
			UserID:       "system",
			Reason:       "time-based score increment",
		}
		roomData.ScoreHistory = append(roomData.ScoreHistory, record)
		roomData.LastRoundTime = now
		fmt.Println("分数变动", roomData.CurrentScore)
	}
}

// GetScoreSinceLastNotification 检查从上一次通知到现在是否有分数变动
func (s *ScoreManager) GetScoreSinceLastNotification(liveRoomID string) int {
	s.mu.Lock()
	defer s.mu.Unlock()

	roomData, exists := s.roomScoreData[liveRoomID]
	if !exists {
		// 如果房间数据不存在，则初始化
		s.InitializeRoom(liveRoomID)
		roomData = s.roomScoreData[liveRoomID]
	}

	// 检查是否有分数变动
	if roomData.LastNotificationTime.Before(roomData.LastChangeTime) {
		roomData.LastNotificationTime = time.Now() // 更新通知时间
		return roomData.CurrentScore
	}
	return -1
}

// StartRoundScoreTicker 启动每分钟检查分数的定时任务
func (s *ScoreManager) StartRoundScoreTicker() {
	ticker := time.NewTicker(10 * time.Second)
	go func() {
		for {
			select {
			case <-ticker.C:
				s.mu.Lock()
				for liveRoomID := range s.initRoomIds {
					fmt.Println("检查分数是否变动")
					s.CheckRoundScoreChange(liveRoomID)
				}
				s.mu.Unlock()
			}
		}
	}()
}
